const cloud = require("wx-server-sdk");

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

exports.main = async (event, context) => {
  console.log("login云函数收到参数:", event);

  try {
    const wxContext = cloud.getWXContext();
    console.log("微信上下文:", wxContext);

    // 获取用户信息
    const { userInfo } = event;
    console.log("用户信息:", userInfo);

    if (!userInfo) {
      throw new Error("缺少用户信息");
    }

    // 构建用户数据
    const userData = {
      openId: wxContext.OPENID,
      token: `${wxContext.OPENID}_${Date.now()}`,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      gender: userInfo.gender,
      country: userInfo.country,
      province: userInfo.province,
      city: userInfo.city,
      phoneNumber: "",
      userId: wxContext.OPENID,
    };

    const result = {
      code: 200,
      data: {
        wechatUserDto: userData,
      },
      msg: "登录成功",
    };

    console.log("login云函数返回结果:", result);
    return result;
  } catch (err) {
    console.error("登录失败，详细错误:", err);
    const errorResult = {
      code: 500,
      msg: err.message || "登录失败",
      data: {
        wechatUserDto: null,
      },
    };
    console.log("login云函数返回错误:", errorResult);
    return errorResult;
  }
};
